package org.openkoala.security.controller;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.session.Session;
import org.openkoala.security.shiro.CurrentUser;


public class FilterSession implements  Filter {
	private Properties properties = null ;
	private String excludedPages;
	public void destroy() {  
    }  
  
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
		HttpServletRequest requesth = (HttpServletRequest) request;
		HttpServletResponse responseh = (HttpServletResponse) response;
		responseh.setHeader("Access-Control-Allow-Origin", "header is present on the requested resource");  
		responseh.setHeader("Access-Control-Allow-Origin", "*");  
		responseh.setHeader("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With");  
		responseh.setHeader("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");  
		responseh.setHeader("X-Powered-By","Jetty");  
		//HttpSession session = requesth.getSession(false);
		Session session =CurrentUser.getSubject().getSession(false);
		String url=requesth.getServletPath();
		if(url!=null) {
			String urlStr[]=url.split("/");
			int cnt=urlStr.length-1;
			if(cnt>0) {
				if(excludedPages.indexOf(urlStr[cnt])>0) {
					filterChain.doFilter(request, response);
					return;
				}
			}else {
				cnt=0;
				if(excludedPages.indexOf(urlStr[cnt])>0) {
					filterChain.doFilter(request, response);
					return;
				}
			}
		}
		if(session==null) {
			String casUrl = properties.getProperty("cas.sever.url");
			String drgUrl = properties.getProperty("drg.sever.url");
			String  getLogOutUrl = casUrl + "/login?service=" + drgUrl;
			responseh.sendRedirect(getLogOutUrl);
			return ;
		}else {
			filterChain.doFilter(request, response);
		}
	}  
  
	public void init(FilterConfig arg0) throws ServletException {
		InputStream propInputStream = FilterSession.class.getResourceAsStream("/drgsys.properties");
		properties = new Properties();
		try {
			properties.load(propInputStream);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (null != propInputStream) {
				try {
					propInputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		 excludedPages = arg0.getInitParameter("excludedPages");
	}  
}
